package com.robot.base.common.api;

import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.robot.base.base.vm.GLBaseViewModel;
import com.robot.base.common.domain.HttpStatusCode;
import com.robot.base.exception.LocalException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Dankal Android Developer
 * @since 2018/7/18
 */

public abstract class AbstractViewModelSubscriber<T> implements Observer<T> {

    protected GLBaseViewModel view;

    public AbstractViewModelSubscriber(GLBaseViewModel view) {
        this.view = view;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (view != null) {
            view.addNetworkRequest(d);
        }
    }

    @Override
    public void onError(Throwable e) {
        if (e == null || view == null) {
            return;
        }
        view.dismissLoadingDialog();
        if (e instanceof LocalException) {
            ToastUtils.showShort(((LocalException) e).getMsg());
        } else {
            ToastUtils.showShort(e.getLocalizedMessage());
        }

        if (e instanceof LocalException) {
            LocalException exception = (LocalException) e;
            //401 重新获取access token , 如果还返回412 就是refresh token 也失效了。需要重新登录
            if (exception.getCode() == HttpStatusCode.TOKEN_INVAILD ||
                    exception.getErrorCode() == HttpStatusCode.UNAUTHORIZED) {
//                view.tokenInvalid();
                //view.showToast("登录信息失效");
//                try {
//                    PrefsManager.loginout();
//                    ActivityUtils.finishAllActivities();
//                    ActivityUtils.startActivity(Class.forName("com.rokid.smarteye.ui.LoginActivity"));
//                } catch (ClassNotFoundException e1) {
//                    e1.printStackTrace();
//                }
            } else {
                ToastUtils.showShort(exception.getMsg());
//                view.showToast(exception.getMsg());
            }
        } else {
            Log.e("SubscriberThrowable", e.getMessage());
        }
    }

    @Override
    public void onComplete() {
        this.view = null;
    }
}
